import Loading from './components/Loading'
import './index.css'
import { ErrorBook } from './pages/ErrorBook'
import { FriendLinks } from './pages/FriendLinks'
import MobilePage from './pages/Mobile'
import TypingPage from './pages/Typing'
import { isOpenDarkModeAtom } from '@/store'
// 全局状态
import { Analytics } from '@vercel/analytics/react'
// 分析
//切换了 分支然后提交到gitee
import 'animate.css'
import { useAtomValue } from 'jotai'
import mixpanel from 'mixpanel-browser'
//
import process from 'process'
//qwerty-learner
import React, { Suspense, lazy, useEffect, useState } from 'react'
import 'react-app-polyfill/stable'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'

const AnalysisPage = lazy(() => import('./pages/Analysis'))
const GalleryPage = lazy(() => import('./pages/Gallery-N'))

if (process.env.NODE_ENV === 'production') {
  // 生产环境
  // for prod
  mixpanel.init('bdc492847e9340eeebd53cc35f321691') // 替换为你的生产环境Token
} else {
  // for dev
  mixpanel.init('5474177127e4767124c123b2d7846e2a', { debug: true }) // 替换为你的开发环境Token
  console.log('Production mode: Mixpanel initialized with production token')
}

function Root() {
  const darkMode = useAtomValue(isOpenDarkModeAtom) // 读取全局状态
  //console.log(darkMode)
  useEffect(() => {
    darkMode ? document.documentElement.classList.add('dark') : document.documentElement.classList.remove('dark')
  }, [darkMode])

  const [isMobile, setIsMobile] = useState(window.innerWidth <= 600) // 初始判断是否为移动端小于600px为false
  useEffect(() => {
    const handleResize = () => {
      const isMobile = window.innerWidth <= 600
      if (!isMobile) {
        // 如果切换到非移动端，跳转到首页
        window.location.href = '/'
      }
      setIsMobile(isMobile) // 更新状态
    }
    window.addEventListener('resize', handleResize) // 监听窗口大小变化
    return () => window.removeEventListener('resize', handleResize) // 清理事件监听器
  }, [])
  return (
    <React.StrictMode>
      <BrowserRouter basename={REACT_APP_DEPLOY_ENV === 'pages' ? '/qwerty-learner' : ''}>
        <Suspense fallback={<Loading />}>
          <Routes>
            {isMobile ? (
              <Route path="/*" element={<Navigate to="/mobile" />} />
            ) : (
              <>
                <Route index element={<TypingPage />} />
                <Route path="/gallery" element={<GalleryPage />} />
                <Route path="/analysis" element={<AnalysisPage />} />
                <Route path="/error-book" element={<ErrorBook />} />
                <Route path="/friend-links" element={<FriendLinks />} />
                <Route path="/*" element={<Navigate to="/" />} />
              </>
            )}
            <Route path="/mobile" element={<MobilePage />} />
          </Routes>
        </Suspense>
      </BrowserRouter>
      <Analytics />
    </React.StrictMode>
  )
}

const container = document.getElementById('root')

container && createRoot(container).render(<Root />)
